package com.future.controller;

import javax.validation.constraints.NotNull;

import com.future.common.annotation.ControllerMapping;
import com.future.common.base.BaseController;
import com.future.common.global.GlobalPara;
import com.future.dao.ManagerDao;
import com.future.dao.SysUserDao;
import com.future.model.SysUser;
import com.future.requestbean.Manager;
import com.future.requestbean.ManagerUpdate;
import com.future.service.SysUserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.tx.Tx;

@ControllerMapping("/manager")
public class ManagerController extends BaseController {
	@Inject
	private ManagerDao managerDao;
	@Inject
	private SysUserDao sysDao;
	@Inject
	private SysUserService sysUserService;

	public void getManagers() {
		renderResult("managers", this.managerDao.getmanagers());
	}

	@Before(Tx.class)
	public void deleteManager(@NotNull(message = "选择要删除的校长") Long managerId) {
		this.managerDao.deleteById(managerId);
		SysUser sysUser = this.sysDao.getSysUserByUserTypeAndUserInfoId(managerId, GlobalPara.MANAGER_TYPE);
		this.sysDao.deleteById(sysUser.getUserid());
		renderSuccess();
	}

	@Before(Tx.class)
	public void addManager() {
		Manager manager = getJsonBody(Manager.class);
		this.sysUserService.checkUserNameExisted(manager.getLoginUsername());
		com.future.model.Manager t = beanToModel(manager, com.future.model.Manager.class);
		this.managerDao.save(t);
		Long managerId = t.getManagerid();

		String username = manager.getLoginUsername();
		this.sysUserService.saveUser(username, GlobalPara.MANAGER_TYPE, managerId);
		renderSuccess();
	}

	@Before(Tx.class)
	public void updateManager() {
		com.future.model.Manager manager = getJsonBodyToModel(ManagerUpdate.class, com.future.model.Manager.class);
		this.managerDao.update(manager);
		renderSuccess();
	}
}
